import {createRouter, createWebHashHistory, createWebHistory} from "vue-router";
import store from '../store'
import Main from '../pages/main.vue'
import app from '../configs/app'

const modules = import.meta.glob('../pages/**/*.vue')

const onFamilyMemberEditEnter = (to, from) => {
    // console.log(to, from)
}

/**
 * @param path Path of component
 * @param name Use by keep-alive
 * @returns {(function(*=): *)|*|(function(*): *)}
 */
// const myImport = (path, name) => {
//     const proxy = import(path)
//     proxy.then((component) => {
//         component.default.name = name
//     })
//     return proxy
// }

/**
 * @param path Path of component
 * @param name Use by keep-alive
 * @returns {(function(*=): *)|*|(function(*): *)}
 */
const myImport = (path, name) => {
    return modules[path]().then((component) => {
        component.default.name = name
        return component
    })
}

const routes = [
    {
        path: "/login",
        name: "wx-auth",
        component: () => myImport('../pages/login.vue', 'wx-auth'),
        meta: { title: "授权登录"},
    }/**, {
        path: '/',
        name: "welcome",
        component: () => myImport('../pages/welcome.vue', 'welcome')
    }*/, {
        path: '/',
        name: "home",
        component: () => myImport('../pages/home.vue', 'home'),
        meta: { title: "中原种植牙博览会"},
    }, {
        path: '/result',
        name: "result",
        component: () => myImport('../pages/result.vue', 'result')
    }, {
        path: '/draw_result',
        name: "draw_result",
        component: () => myImport('../pages/draw_result.vue', 'draw_result')
    }
]

const router = createRouter({
    history: app.history == 'history' ? createWebHistory() : createWebHashHistory(),
    routes,
})

const routerQueue = []

router.beforeEach(async (to, from, next) => {

    if (routerQueue[routerQueue.length - 1] == to.path + '=>' + from.path) {
        routerQueue.pop()
    } else {
        routerQueue.push(from.path + '=>' + to.path)
    }

    console.log(routerQueue)

    if (to.meta.keepAlive) {
        store.commit('keepAlive', to.name)
    }

    let user = await store.dispatch("user/getUser")

    if (to.meta['login']) {
        if (!user) { // Not login
            localStorage.setItem('backPage', to.fullPath)
            next('/login')
        } else {
            next()
        }
    } else {
        next()
    }

})

export function resetRouter () {
    const newRouter = createRouter({
        history: createWebHashHistory(),
        routes,
    })
    router.matcher = newRouter.matcher // the relevant part
}

export default router
